<template>
  <div class="user-info-container">
    <el-dropdown trigger="click" @command="handleCommand" @visible-change="handleVisibleChange">
      <div class="user-info">
        <!-- 用户头像 -->
        <el-avatar :size="32" :src="props.userDetail.avatar" class="user-avatar">
          {{ props.userDetail.store_name?.charAt(0) }}
        </el-avatar>
        <!-- 用户名 -->
        <span class="user-name">{{ props.userDetail.store_name }}</span>
        <el-icon class="el-icon--right" style="color: white"><arrow-down /></el-icon>
      </div>

      <template #dropdown>
        <el-dropdown-menu class="user-dropdown-menu">
          <!-- 用户信息区域 -->
          <div class="user-info-section">
            <div class="version-info">版本: 普通版</div>
            <div class="account-stats">
                             <div class="stat-item">剩余点数: {{Math.floor(userData.price)}}</div>
              <div class="stat-item">到期: {{userData.out_date}}</div>
              <div class="space-info">
                <div class="space-text">空间: {{userData.file_size}}GB/{{userData.sizenum}}GB</div>
                <el-progress
                  :percentage="calculateSpacePercentage()"
                  :stroke-width="6"
                  :show-text="false"
                  class="space-progress"
                />
              </div>
              <el-button type="primary" size="small" class="expand-btn" @click="showExpandDialog = true">扩容</el-button>
            </div>
                       </div>

           <!-- 功能按钮区域 -->
           <el-dropdown-item command="usage" :icon="Document">
             使用详情
           </el-dropdown-item>
           <el-dropdown-item command="password" :icon="Lock">
             修改密码
           </el-dropdown-item>
           <el-dropdown-item command="profile" :icon="User">
             个人中心
           </el-dropdown-item>
           <el-dropdown-item command="stastic" :icon="PieChart">
            视频仓储中心
           </el-dropdown-item>
           <el-dropdown-item command="logout" divided :icon="SwitchButton">
             退出登录
           </el-dropdown-item>
        </el-dropdown-menu>
      </template>
    </el-dropdown>
  </div>
  <!-- 用户信息弹窗 -->
  <MyDialog v-model="showChooseImgDialog" title="用户信息" width="75%">
    <!-- 这里可以传入任何自定义内容 -->
    <UserProfile :user="props.userDetail"></UserProfile>
    <!-- 自定义底部 -->
    <template #footer>
      <el-button @click="showChooseImgDialog = false">关闭</el-button>
    </template>
  </MyDialog>

  <!-- 使用详情弹窗 -->
  <MyDialog v-model="showUsageDialog" title="使用详情" width="90%">
    <UsageDetail />
    <!-- 自定义底部 -->
    <template #footer>
      <el-button @click="showUsageDialog = false">关闭</el-button>
    </template>
  </MyDialog>

  <!-- 扩容弹窗 -->
  <MyDialog v-model="showExpandDialog" title="素材资源库容量" width="400px" @close="handleExpandDialogClose">
    <div class="expand-dialog-content">
      <!-- 当前容量显示 -->
      <div class="capacity-display">
        <div class="current-capacity">{{ userData.sizenum || 5 }}GB</div>
        <div class="capacity-label">当前最大容量</div>
      </div>

      <!-- 扩容提示 -->
      <div class="expand-tip">
        选择扩容数量(扩容<span class="highlight">1GB</span>,需消耗<span class="highlight">500点数</span>)
      </div>

      <!-- 数量选择器 -->
      <div class="quantity-selector">
        <el-input-number
          v-model="expandQuantity"
          :min="1"
          :max="Math.floor(userData.price / 500)"
          size="large"
          controls-position="right"
          class="quantity-input-number"
        />
      </div>
    </div>

    <!-- 自定义底部 -->
    <template #footer>
      <el-button @click="showExpandDialog = false">取消</el-button>
      <el-button type="primary" @click="handleExpandConfirm">确认</el-button>
    </template>
  </MyDialog>

  <!-- 修改密码弹窗 -->
  <MyDialog v-model="showPasswordDialog" title="修改密码" width="400px" @close="handlePasswordDialogClose">
    <div class="password-dialog-content">
      <!-- 原密码输入框 -->
      <div class="password-input-group">
        <el-input
          v-model="oldPassword"
          type="password"
          placeholder="请输入原密码"
          class="password-input"
          show-password
        />
      </div>

      <!-- 新密码输入框 -->
      <div class="password-input-group">
        <el-input
          v-model="newPassword"
          type="password"
          placeholder="请输入新密码"
          class="password-input"
          show-password
        />
      </div>
    </div>
    <!-- 自定义底部 -->
    <template #footer>
      <el-button type="primary" @click="handlePasswordConfirm">确认修改</el-button>
    </template>
  </MyDialog>
</template>

<script setup>
import { ref } from 'vue'
import { ArrowDown, User, SwitchButton, PieChart, ArrowRight, Document, Lock } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter } from 'vue-router';
import LocalStorageUtil from '../../utils/LocalStorageUtil';
import MyDialog from '../common/MyDialog.vue';
import UserProfile from './UserProfile.vue';
import UsageDetail from './UsageDetail.vue';
import utils from '../../utils/utils';
import axiosUtil from "../../axios-util/axios-util.js";

const router = useRouter()

// 用户信息（实际项目中可以从Vuex/Pinia获取）
const props = defineProps({
  userDetail: {
    type: Object,
    default: () => ({})
  }
})

const showChooseImgDialog = ref(false);
const showUsageDialog = ref(false);
const showExpandDialog = ref(false);
const showPasswordDialog = ref(false);

const userData = ref({})
const expandQuantity = ref(1);
const oldPassword = ref('');
const newPassword = ref('');

// 计算空间使用百分比
const calculateSpacePercentage = () => {
  if (!userData.value.file_size || !userData.value.sizenum) {
    return 0
  }
  const used = parseFloat(userData.value.file_size)
  const total = parseFloat(userData.value.sizenum)
  if (total === 0) return 0

  const percentage = Math.round((used / total) * 100)
  // 限制最大值为100%
  return Math.min(percentage, 100)
}

// 处理下拉菜单显示状态变化
const handleVisibleChange = async (visible) => {
  if (visible) {
    // 当下拉菜单显示时，请求最新数据
    const response = await axiosUtil.post('api/store/info', {})
    if(response.data.code === 1){
      userData.value = response.data.data
    }
  }
}

// 处理下拉菜单命令
const handleCommand = async (command) => {

  switch (command) {
    case 'profile':
      showChooseImgDialog.value = true;
      break;
    case 'stastic':
      router.push('/dataStatistics')
      break
    case 'usage':
      // 处理使用详情
      showUsageDialog.value = true;
      break
    case 'password':
      // 处理修改密码
      showPasswordDialog.value = true;
      break
    case 'logout':
      handleLogout()
      break
  }
}

// 退出登录确认
const handleLogout = () => {
  ElMessageBox.confirm('确定要退出登录吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    // 实际项目中这里调用退出接口
    LocalStorageUtil.clearExcept(["username", "password"]);
    utils.globalCacheMenu = [];
    ElMessage.success('退出成功')
    router.push('/login')
  }).catch(() => {
    // 取消退出
  })
}

// 扩容弹窗关闭时重置数量
const handleExpandDialogClose = () => {
  expandQuantity.value = 1;
};

// 扩容确认
const handleExpandConfirm = async () => {
  if (expandQuantity.value <= 0) {
    ElMessage.warning('请选择扩容数量');
    return;
  }

  const currentSize = parseFloat(userData.value.sizenum) || 5;
  const newSize = currentSize + expandQuantity.value;
  const price = expandQuantity.value * 500; // 假设每GB扩容价格为500点数
  const currentPrice = parseFloat(userData.value.price) || 0;

  if (currentPrice < price) {
    ElMessage.error(`您的点数不足，当前点数: ${currentPrice}，需要点数: ${price}`);
    return;
  }

  try {
    // 这里可以添加确认对话框
    const confirmResult = await ElMessageBox.confirm(
      `确定要扩容 ${expandQuantity.value}GB 吗？将消耗 ${price} 点数`,
      '确认扩容',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    );

    if (confirmResult === 'confirm') {
      const response = await axiosUtil.post('api/store/lcmemory', {
        num: expandQuantity.value
      });

      if (response.data.code === 1) {
        ElMessage.success('扩容成功！');
        showExpandDialog.value = false;
        expandQuantity.value = 1; // 重置数量
      } else {
        ElMessage.error(response.data.msg || '扩容失败');
      }
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('扩容失败:', error);
      ElMessage.error('扩容失败，请稍后再试');
    }
  }
};

// 修改密码确认
const handlePasswordConfirm = async () => {
  if (!oldPassword.value.trim()) {
    ElMessage.warning('请输入原密码');
    return;
  }
  if (!newPassword.value.trim()) {
    ElMessage.warning('请输入新密码');
    return;
  }
  if (newPassword.value.length < 6) {
    ElMessage.warning('新密码长度不能少于6位');
    return;
  }

  try {
    const response = await axiosUtil.post('api/store/editpassword', {
      password: oldPassword.value,
      new_password: newPassword.value
    });
    if(response.data.code === 1) {

      // 模拟API调用成功
      ElMessage.success('密码修改成功！');
      showPasswordDialog.value = false;
      // 清空输入框
      oldPassword.value = '';
      newPassword.value = '';
      LocalStorageUtil.clearExcept(["username", "password"]);
      utils.globalCacheMenu = [];
      ElMessage.success('退出成功')
      router.push('/login')
    }else {
      ElMessage.error(response.data.msg || '');
    }

  } catch (error) {
    console.error('修改密码失败:', error);
    ElMessage.error('修改密码失败，请稍后再试');
  }
};

// 修改密码弹窗关闭时清空输入框
const handlePasswordDialogClose = () => {
  oldPassword.value = '';
  newPassword.value = '';
};
</script>

<style scoped>
.user-info-container {
  display: flex;
  align-items: center;
  height: 100%;
  padding-right: 20px;
}

.user-info {
  display: flex;
  align-items: center;
  cursor: pointer;
  transition: all 0.3s;
  padding: 5px 10px;
  border-radius: 4px;
}

.user-avatar {
  margin-right: 12px;
  background-color: var(--el-color-primary);
}

.user-name {
  font-size: 14px;
  margin-right: 5px;
  color: white;
}

/* 响应式调整 */
@media screen and (max-width: 768px) {
  .user-name {
    display: none;
  }
}

/* 用户下拉菜单样式 */
.user-dropdown-menu {
  min-width: 300px;
  padding: 0;
  border-radius: 12px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.12);
  border: 1px solid var(--el-border-color-lighter);
  overflow: hidden;
  background-color: rgba(255, 255, 255, 0.9) !important;
  backdrop-filter: blur(10px);
}

.user-info-section {
  padding: 16px;
  background: linear-gradient(135deg, var(--el-color-primary-light-9) 0%, var(--el-bg-color) 100%);
  border-bottom: 1px solid var(--el-border-color-lighter);
}

.version-info {
  font-size: 12px;
  color: var(--el-text-color-regular);
  margin-bottom: 12px;
  padding: 4px 10px;
  background: rgba(255, 255, 255, 0.6);
  border-radius: 12px;
  display: inline-block;
  font-weight: 500;
  backdrop-filter: blur(10px);
}

.account-stats {
  margin-bottom: 16px;
}

.stat-item {
  font-size: 13px;
  color: var(--el-text-color-primary);
  margin-bottom: 8px;
  line-height: 1.4;
  display: flex;
  align-items: center;
  font-weight: 500;
}

.stat-item::before {
  content: '';
  width: 5px;
  height: 5px;
  background: var(--el-color-primary);
  border-radius: 50%;
  margin-right: 8px;
  flex-shrink: 0;
}

.space-info {
  margin-bottom: 12px;
  background: rgba(255, 255, 255, 0.8);
  padding: 10px;
  border-radius: 6px;
  border: 1px solid var(--el-border-color-lighter);
}

.space-text {
  font-size: 13px;
  color: var(--el-text-color-primary);
  margin-bottom: 6px;
  font-weight: 500;
  display: flex;
  align-items: center;
}

.space-text::before {
  content: '';
  width: 4px;
  height: 4px;
  background: var(--el-color-success);
  border-radius: 50%;
  margin-right: 6px;
  flex-shrink: 0;
}

.space-progress {
  margin-bottom: 8px;
}

.expand-btn {
  width: 33.33%;
  margin: 6px auto 0;
  border-radius: 6px;
  font-weight: 500;
  height: 32px;
  background: linear-gradient(135deg, var(--el-color-primary) 0%, var(--el-color-primary-light-3) 100%);
  border: none;
  transition: all 0.3s ease;
  display: block;
}

.expand-btn:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.3);
}





/* 下拉菜单项样式调整 */
:deep(.el-dropdown-menu__item) {
  padding: 10px 16px;
  font-weight: 500;
  transition: all 0.3s ease;
  border-radius: 0;
  background-color: transparent;
}

:deep(.el-dropdown-menu__item:hover) {
  background: rgba(64, 158, 255, 0.1);
  color: var(--el-color-primary);
}

:deep(.el-dropdown-menu__item:last-child) {
  border-radius: 0 0 12px 12px;
}

/* 进度条样式优化 */
:deep(.el-progress-bar__outer) {
  background: var(--el-border-color-lighter);
  border-radius: 4px;
}

:deep(.el-progress-bar__inner) {
  background: linear-gradient(90deg, var(--el-color-success) 0%, var(--el-color-primary) 100%);
  border-radius: 4px;
  transition: all 0.3s ease;
}

.user-avatar {
  transition: all 0.3s ease;
}

/* 扩容弹窗样式 */
.expand-dialog-content {
  text-align: center;
  padding: 20px;
}

.capacity-display {
  margin-bottom: 20px;
}

.current-capacity {
  font-size: 28px;
  font-weight: bold;
  color: #000000;
  margin-bottom: 5px;
}

.capacity-label {
  font-size: 14px;
  color: #000000;
}

.expand-tip {
  font-size: 14px;
  color: #000000;
  margin-bottom: 20px;
  padding: 10px;
  background: rgba(255, 255, 255, 0.1);
  border-radius: 8px;
}

.expand-tip .highlight {
  color: var(--el-color-danger);
  font-weight: bold;
}

.quantity-selector {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-top: 20px;
}

.quantity-input-number {
  width: 120px;
}

.quantity-input-number :deep(.el-input-number__decrease),
.quantity-input-number :deep(.el-input-number__increase) {
  background-color: var(--el-color-primary);
  border-color: var(--el-color-primary);
  color: white;
  font-weight: bold;
  font-size: 16px;
}

.quantity-input-number :deep(.el-input-number__decrease:hover),
.quantity-input-number :deep(.el-input-number__increase:hover) {
  background-color: var(--el-color-primary-light-3);
  border-color: var(--el-color-primary-light-3);
}

.quantity-input-number :deep(.el-input__inner) {
  text-align: center;
  font-size: 18px;
  font-weight: bold;
  color: #000000;
  border-color: var(--el-border-color-lighter);
}

.quantity-input-number :deep(.el-input__inner:focus) {
  border-color: var(--el-color-primary);
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
}

/* 修改密码弹窗样式 */
.password-dialog-content {
  padding: 30px 20px;
  text-align: center;
}

.password-input-group {
  margin-bottom: 20px;
}

.password-input {
  width: 100%;
}

.password-input :deep(.el-input__inner) {
  height: 45px;
  border-radius: 8px;
  border: 1px solid #e0e0e0;
  font-size: 14px;
  color: #333;
  background-color: #fff;
  transition: all 0.3s ease;
}

.password-input :deep(.el-input__inner:focus) {
  border-color: var(--el-color-primary);
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.1);
}

.password-input :deep(.el-input__inner::placeholder) {
  color: #999;
}

.confirm-button {
  margin-top: 30px;
  padding: 12px 30px;
  background: linear-gradient(135deg, var(--el-color-primary) 0%, var(--el-color-primary-light-3) 100%);
  color: white;
  border-radius: 8px;
  cursor: pointer;
  font-size: 16px;
  font-weight: 500;
  transition: all 0.3s ease;
  display: inline-block;
  user-select: none;
}

.confirm-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(64, 158, 255, 0.3);
}

.confirm-button:active {
  transform: translateY(0);
}
</style>
